package com.quanyan.assets.service.impl;

import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.api.enums.AssetsPayReceive;
import com.quanyan.api.enums.AssetsType;
import com.quanyan.assets.emun.AssetsErrorEnum;
import com.quanyan.assets.emun.OpType;
import com.quanyan.assets.emun.StatusType;
import com.quanyan.assets.entity.*;
import com.quanyan.assets.mapper.ETbUserAssetsMapper;
import com.quanyan.assets.mapper.ETbUserEggsAccumulateHistoryMapper;
import com.quanyan.assets.mapper.TbAccumulateRuleMapper;
import com.quanyan.assets.mapper.TbUserEggsAccumulateHistoryMapper;
import com.quanyan.assets.repository.AccumulateRuleRepository;
import com.quanyan.assets.repository.EggsAccumulateHistoryRepository;
import com.quanyan.assets.repository.UserAssetsRepository;
import com.quanyan.assets.request.*;
import com.quanyan.assets.response.*;
import com.quanyan.assets.service.CurrencyService;
import com.quanyan.assets.service.EggsService;
import com.quanyan.assets.service.UserAssetsService;
import com.quanyan.assets.service.UtilCurrencyService;
import com.quanyan.comment.enums.TaskEnum;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.BaseEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.*;
import com.quanyan.mq.client.QcMsgClient;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.orderpay.request.ReqOrderSave;
import com.quanyan.orderpay.request.ReqPayInfo;
import com.quanyan.orderpay.request.ReqProductDetail;
import com.quanyan.orderpay.response.RespPreOrder;
import com.quanyan.orderpay.response.mq.OrderNotifyMsg;
import com.quanyan.orderpay.response.mq.RefundNotifyMsg;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.pay.enums.PayWayEnum;
import com.quanyan.user.mq.UserTaskMsg;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wmb on 2016/6/28.
 */
@Service("eggsService")
public class EggsServiceImpl implements EggsService{
    @Autowired
    private UserAssetsRepository userAssetsRepository;
    @Autowired
    private UtilCurrencyService utilCurrencyService;
    @Autowired
    private OrderPayService orderPayService;
    @Autowired
    private CurrencyService currencyService;
    @Autowired
    private EggsAccumulateHistoryRepository eggsAccumulateHistoryRepository;
    @Autowired
    private UserAssetsService userAssetsService;
    @Autowired
    private AccumulateRuleRepository accumulateRuleRepository;
    @Autowired
    private QcMsgClient qcMsgClient;
    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private ETbUserAssetsMapper eTbUserAssetsMapper;
    @Autowired
    private TbUserEggsAccumulateHistoryMapper tbUserEggsAccumulateHistoryMapper;
    @Autowired
    private ETbUserEggsAccumulateHistoryMapper eTbUserEggsAccumulateHistoryMapper;
    @Autowired
    private TbAccumulateRuleMapper tbAccumulateRuleMapper;
    @Value("${payCallBack}")
    private String payCallBack;
    @Value("${closeCallBack}")
    private String closeCallBack;
    @Value("${applyRefundCallBack}")
    private String applyRefundCallBack;
    @Value("${refundCallBack}")
    private String refundCallBack;
    @Override
    public APIResponse<RespEggsAccount> account(int uid) {
        //获取用户鸟蛋积分
        TbUserAssets tbUserAssets=userAssetsRepository.selectByUidAndAssetsType(uid, AssetsType.ASSETS_EGGS.id.byteValue());
        RespEggsAccount eggsAccount=new RespEggsAccount();
        eggsAccount.setAccumulate(tbUserAssets.getAccumulate());
        eggsAccount.setCurrency(utilCurrencyService.exchangeAssetsAmount(AssetsType.ASSETS_EGGS.id.byteValue()));
        return APIResponse.returnSuccess(eggsAccount);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Valid
    public APIResponse<RespPreOrder> rechange(APIRequest<ReqEggsRechange> apiRequest,int uid) {
        ReqEggsRechange reqEggsRechange=apiRequest.getData();
        if(null==PayWayEnum.getById(reqEggsRechange.getPayId())){
            throw new BizException(AssetsErrorEnum.PAY_ID_INVALID);
        }
        APIResponse<RespUserInfoBase> apiResponse=userServiceFacade.queryUserInfo(uid);

        //鸟蛋充值预下单返回流水号
        String serialNumber=rechangeHistory(apiResponse.getData(), reqEggsRechange);
        //调用支付接口
        APIRequest apiRequestPay=new APIRequest();
        ReqOrderSave reqOrderSave=new ReqOrderSave();
        reqOrderSave.setSourceSystemId(Constants.ASSETS_SYSTEM_CODE);
        reqOrderSave.setSourceBusinessId(Constants.ASSETS_EGGS_RECHANGE_CODE);
        reqOrderSave.setOutTradeNo(serialNumber);
        reqOrderSave.setUid(uid);
        reqOrderSave.setOrderDescribe("购买鸟蛋");
        reqOrderSave.setPayTimeOut(1440);
        reqOrderSave.setOrderAmount(reqEggsRechange.getOrderAmount());
        reqOrderSave.setService("service.assets");
        reqOrderSave.setNotifyURL(payCallBack);
        reqOrderSave.setCloseNotifyURL(closeCallBack);
        reqOrderSave.setExceptionRefundNotify(applyRefundCallBack);
        reqOrderSave.setPlatformType(reqEggsRechange.getPlatformType());
        reqOrderSave.setRefundNotifyURL(refundCallBack);
        reqOrderSave.setVer(apiRequest.getVer());
        ReqProductDetail reqProductDetail=new ReqProductDetail();
        reqProductDetail.setProductName("鸟蛋");
        reqProductDetail.setPrice(currencyService.exchangeRatioById(AssetsType.ASSETS_EGGS.id.byteValue()).getData());
        reqProductDetail.setQuantity(reqEggsRechange.getOrderAmount().divide(currencyService.exchangeRatioById(AssetsType.ASSETS_EGGS.id.byteValue()).getData()).intValue());
        List<ReqProductDetail> productDetailList =new ArrayList<ReqProductDetail>();
        productDetailList.add(reqProductDetail);
        reqOrderSave.setProductDetailList(productDetailList);
        ReqPayInfo reqPayInfo=new ReqPayInfo();
        reqPayInfo.setPayId(reqEggsRechange.getPayId());
        reqPayInfo.setAmount(reqEggsRechange.getOrderAmount());
        reqPayInfo.setPayType(PayWayEnum.getById(reqEggsRechange.getPayId()).getPayType());
        List<ReqPayInfo> payInfos =new ArrayList<ReqPayInfo>();
        payInfos.add(reqPayInfo);
        reqOrderSave.setPayInfos(payInfos);
        apiRequestPay.setData(reqOrderSave);
        return orderPayService.submitOrder(apiRequestPay);
    }

    @Override
    @Valid
    public APIResponse<RespUserAccumulateModify> randomEggs(ReqRandomEggs reqRandomEggs, int uid) {
        APIResponse<RespUserInfoBase> apiResponse1=userServiceFacade.queryUserInfo(uid);
        APIRequest<ReqUserAccumulateModify> apiRequest=new APIRequest<ReqUserAccumulateModify>();
        ReqUserAccumulateModify reqUserAccumulateModify=new ReqUserAccumulateModify();
        reqUserAccumulateModify.setSystemCode(Constants.USER_CENTER_SYSTEM_CODE);
        reqUserAccumulateModify.setBusinessCode(Constants.USER_CENTER_RANDOM_EGGS_CODE);
        reqUserAccumulateModify.setAssetsType(AssetsType.ASSETS_EGGS.id.byteValue());
        reqUserAccumulateModify.setUid(uid);
        if(apiResponse1.isRet()){
            reqUserAccumulateModify.setReceiver(apiResponse1.getData().getNickName());
        }
        reqUserAccumulateModify.setPayReceive(AssetsPayReceive.SYSTEM.getName());
        reqUserAccumulateModify.setInfo("掏鸟蛋奖励");
        apiRequest.setData(reqUserAccumulateModify);
        APIResponse<RespUserAccumulateModify> apiResponse = new APIResponse<RespUserAccumulateModify>();
        TbUserAssets tbUserAssets = userAssetsRepository.selectByUidAndAssetsType(uid,AssetsType.ASSETS_EGGS.getId().byteValue());
        RespUserAccumulateModify respUserAccumulateModify = new RespUserAccumulateModify();
        respUserAccumulateModify.setAccount(tbUserAssets);
        respUserAccumulateModify.setAccumulate(0L);
        apiResponse.setData(respUserAccumulateModify);
//        APIResponse<RespUserAccumulateModify> apiResponse=userAssetsService.modifyAccumulate(apiRequest);
//        if(apiResponse.isRet()){
//            UserTaskMsg userTaskMsg =new UserTaskMsg();
//            userTaskMsg.setUid(uid);
//            userTaskMsg.setAccumulate(apiResponse.getData().getAccumulate());
//            userTaskMsg.setTaskId(TaskEnum.TASK_ENUM__T_EGG_SHELLS.getId());
//            //给任务中心发送消息
//            MqRequestMsg mqRequestMsg = new MqRequestMsg();
//            mqRequestMsg.setTopic(Constants.MQ_TOPIC_TASK_TOPIC);
//            mqRequestMsg.setTag(Constants.MQ_TOPIC_TASK_TAG);
//            mqRequestMsg.setMsgId(uid+"");
//            mqRequestMsg.setBody(ObjectUtil.toByteArray(userTaskMsg));
//            qcMsgClient.asyncSend(mqRequestMsg);
//        }
        return apiResponse;
    }

    @Override
    public APIResponse<RespRuleUseStatus> ruleUseStatus(ReqRuleUseStatus reqRuleUseStatus, int uid) {
        TbAccumulateRule tbAccumulateRule=accumulateRuleRepository.selectBySBA(reqRuleUseStatus.getSystemCode(),reqRuleUseStatus.getBusinessCode(),reqRuleUseStatus.getAssetsType());
        if(null==tbAccumulateRule){
            throw new BizException(AssetsErrorEnum.ASSETS_RULE_RECORD_DO_NOT_EXISTS);
        }
        RespRuleUseStatus respRuleUseStatus=new RespRuleUseStatus();
        //使用次数限制
        if(tbAccumulateRule.getUseAmount().intValue()!=-1){
            //该规则可使用次数
            respRuleUseStatus.setUseAbleAmount(tbAccumulateRule.getUseAmount());
            //该规则已使用次数
            int useAmount=accumulateRuleRepository.countUse(uid, reqRuleUseStatus.getSystemCode(), reqRuleUseStatus.getBusinessCode(),reqRuleUseStatus.getAssetsType());
            respRuleUseStatus.setUseAmount(useAmount);
            if(useAmount>=tbAccumulateRule.getUseAmount().intValue()){
                respRuleUseStatus.setUseStatus(false);
            }else{
                respRuleUseStatus.setUseStatus(true);
            }
        }else if(tbAccumulateRule.getTodayUseAmount().intValue()!=-1){
            //该规则今日可使用的次数
            respRuleUseStatus.setTodayUseAbleAmount(tbAccumulateRule.getTodayUseAmount());
            //非次数使用，今日已使用次数
            int todayUseAmount=accumulateRuleRepository.countUseToday(uid, reqRuleUseStatus.getSystemCode(), reqRuleUseStatus.getBusinessCode(),reqRuleUseStatus.getAssetsType());
            respRuleUseStatus.setTodayUseAmount(todayUseAmount);
            if(todayUseAmount>=tbAccumulateRule.getTodayUseAmount().intValue()){
                respRuleUseStatus.setTodayUseStatus(false);
            }else{
                respRuleUseStatus.setTodayUseStatus(true);
            }
        }
        return APIResponse.returnSuccess(respRuleUseStatus);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public APIResponse<BaseEnum> payCallBack(OrderNotifyMsg orderNotifyMsg) {
        //鸟蛋充值有对应流水号
        if (!StringUtil.isBlankOrNull(orderNotifyMsg.getOutTradeNo())) {
            if (orderNotifyMsg.getResultCode() != null) {
                switch (orderNotifyMsg.getResultCode()) {
                    //支付成功处理
                    case OrderNotifyMsg.RESULT_CODE_USER_PAY_SUCCESS:
                        //更新历史状态
                        int updateStatus = eggsAccumulateHistoryRepository.updateRechangeStatus(orderNotifyMsg.getOutTradeNo(), StatusType.EFFECTIVE.id.byteValue(),StatusType.RECHARGE.id.byteValue());
                        TbUserEggsAccumulateHistory tbUserEggsAccumulateHistory = eggsAccumulateHistoryRepository.selectRechangeBySerialNumber(orderNotifyMsg.getOutTradeNo());
                        if (updateStatus == 1) {
                            Long accumulate = orderNotifyMsg.getPayAmount().multiply(utilCurrencyService.exchangeAssetsAmount(AssetsType.ASSETS_EGGS.id.byteValue())).longValue();
                            //如果不存在账号就初始化
                            userAssetsRepository.initAllCount(tbUserEggsAccumulateHistory.getUid());
                            //更新用户鸟蛋账户
                            int count = eTbUserAssetsMapper.updateEffectiveAccumulate(tbUserEggsAccumulateHistory.getUid(), AssetsType.ASSETS_EGGS.id.byteValue(), accumulate);
                            //该规则已使用次数
                            int useAmount=accumulateRuleRepository.countUse(tbUserEggsAccumulateHistory.getUid(), Constants.USER_CENTER_SYSTEM_CODE, Constants.USER_CENTER_SHELL_BY_EGGS_RECHANGE_CODE, AssetsType.ASSETS_SHELL.id.byteValue());
                            if (useAmount==0) {
                                //发给用户中心消息
                                UserTaskMsg userTaskMsg = new UserTaskMsg();
                                userTaskMsg.setUid(tbUserEggsAccumulateHistory.getUid());
                                userTaskMsg.setTaskId(TaskEnum.TASK_ENUM__ADD_EGGSHELLS.getId());
                                //给任务中心发送消息
                                MqRequestMsg mqRequestMsg = new MqRequestMsg();
                                mqRequestMsg.setTopic(Constants.MQ_TOPIC_TASK_TOPIC);
                                mqRequestMsg.setTag(Constants.MQ_TOPIC_TASK_TAG);
                                mqRequestMsg.setMsgId(tbUserEggsAccumulateHistory.getUid().toString());
                                mqRequestMsg.setBody(ObjectUtil.toByteArray(userTaskMsg));
                                qcMsgClient.asyncSend(mqRequestMsg);
                            }
                            //账号更新成功更新历史记录
                            if (count == 1) {
                                int updateAccumulateHistoryCount = eggsAccumulateHistoryRepository.updateAccumulateHistory(Constants.ASSETS_EGGS_RECHANGE_CODE, orderNotifyMsg.getOutTradeNo(), accumulate);
                                if (updateAccumulateHistoryCount != 1) {
                                    //回滚
                                    throw new BizException(AssetsErrorEnum.UPDATE_ACCUMULATE_HISTORY_ERROR);
                                } else {
                                    //打印日志
                                }
                            } else {
                                //回滚
                                throw new BizException(AssetsErrorEnum.UPDATE_EGGES_ACCUMULATE_ERROR);
                            }
                        } else {
                            //判断之前是否已经消费过
                            TbUserEggsAccumulateHistoryExample tbUserEggsAccumulateHistoryExample=new TbUserEggsAccumulateHistoryExample();
                            tbUserEggsAccumulateHistoryExample.createCriteria().andSerialNumberEqualTo(orderNotifyMsg.getOutTradeNo())
                                    .andStatusEqualTo(StatusType.EFFECTIVE.id.byteValue());
                            int count=tbUserEggsAccumulateHistoryMapper.countByExample(tbUserEggsAccumulateHistoryExample);
                            if(count!=1){
                                //回滚
                                throw new BizException(AssetsErrorEnum.UPDATE_ACCUMULATE_HISTORY_ERROR);
                            }
                        }
                        break;
                    //支付失败，进行取消订单处理
                    case OrderNotifyMsg.RESULT_CODE_USER_PAY_FAIL:
                        //更新历史状态
                        eggsAccumulateHistoryRepository.updateRechangeStatus(orderNotifyMsg.getOutTradeNo(), StatusType.DISABLE.id.byteValue(),StatusType.RECHARGE.id.byteValue());
                        break;
                }
            }
        }
        return APIResponse.returnSuccess(ApiResponseEnum.SUCCESS);
    }

    @Override
    public APIResponse<BaseEnum> closeCallBack(OrderNotifyMsg orderNotifyMsg) {
        int updateStatus = eggsAccumulateHistoryRepository.updateRechangeStatus(orderNotifyMsg.getOutTradeNo(), StatusType.DISABLE.id.byteValue(),StatusType.RECHARGE.id.byteValue());
        if(updateStatus==1){
            return APIResponse.returnSuccess(ApiResponseEnum.SUCCESS);
        }else{
            return APIResponse.returnSuccess(ApiResponseEnum.FAIL);
        }
    }

    @Override
    public APIResponse<BaseEnum> applyRefundCallBack(RefundNotifyMsg refundNotifyMsg) {
        int updateStatus = eggsAccumulateHistoryRepository.updateRechangeStatus(refundNotifyMsg.getOutTradeNo(), StatusType.SUBMIT_REFUND.id.byteValue(), StatusType.DISABLE.id.byteValue());
        if(updateStatus==1){
            return APIResponse.returnSuccess(ApiResponseEnum.SUCCESS);
        }else{
            return APIResponse.returnSuccess(ApiResponseEnum.FAIL);
        }
    }

    @Override
    public APIResponse<BaseEnum> refundCallBack(RefundNotifyMsg refundNotifyMsg) {
        int updateStatus = eggsAccumulateHistoryRepository.updateRechangeStatus(refundNotifyMsg.getOutTradeNo(), StatusType.REFUND.id.byteValue(),StatusType.SUBMIT_REFUND.id.byteValue());
        if(updateStatus==1){
            return APIResponse.returnSuccess(ApiResponseEnum.SUCCESS);
        }else{
            return APIResponse.returnSuccess(ApiResponseEnum.FAIL);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class,isolation = Isolation.READ_COMMITTED)
    @Valid
    public APIResponse<BaseEnum> addEggs(ReqAdminAddEggs reqAdminAddEggs) {
        //判断systemCode+businessCode+assetsType是否存在
        TbAccumulateRuleExample tbAccumulateRuleExample = new TbAccumulateRuleExample();
        tbAccumulateRuleExample.createCriteria().andSystemCodeEqualTo(Constants.ASSETS_SYSTEM_CODE)
                .andBusinessCodeEqualTo(Constants.ASSETS_ADMIN_ADD_EGGS_CODE)
                .andAssetsTypeEqualTo(AssetsType.ASSETS_EGGS.getId().byteValue());
        List<TbAccumulateRule> tbAccumulateRuleList = tbAccumulateRuleMapper.selectByExample(tbAccumulateRuleExample);
        if (tbAccumulateRuleList.isEmpty()) {
            throw new BizException(AssetsErrorEnum.ASSETS_RULE_RECORD_DO_NOT_EXISTS);
        }
        //最大批次号
        int maxBatchNo=eggsAccumulateHistoryRepository.selectMaxBatchNo()+5;
        for(ReqAdminAddEggsUser reqAdminAddEggsUser:reqAdminAddEggs.getReqAdminAddEggsUserList()){
            APIResponse<RespUserInfoBase> respUserInfoBaseAPIResponse= null;
            try {
                respUserInfoBaseAPIResponse = userServiceFacade.queryUserInfoByPhone(reqAdminAddEggsUser.getPhone());
            }catch (Exception e){
                String serialNumber = CommonUtils.generateBusinessOrderNo(Constants.ASSETS_SYSTEM, -1);
                //记录失败
                TbUserEggsAccumulateHistory tbUserEggsAccumulateHistory = new TbUserEggsAccumulateHistory();
                tbUserEggsAccumulateHistory.setUid(-1);
                tbUserEggsAccumulateHistory.setAccumulate(reqAdminAddEggsUser.getAccumulate());
                tbUserEggsAccumulateHistory.setOpType(OpType.RECEIVE.id.byteValue());
                tbUserEggsAccumulateHistory.setBusinessCode(Constants.ASSETS_ADMIN_ADD_EGGS_CODE);
                tbUserEggsAccumulateHistory.setSystemCode(Constants.ASSETS_SYSTEM_CODE);
                tbUserEggsAccumulateHistory.setStatus(StatusType.DISABLE.id.byteValue());
                tbUserEggsAccumulateHistory.setPayReceive(AssetsPayReceive.SYSTEM.getName());
                tbUserEggsAccumulateHistory.setInfo(reqAdminAddEggs.getInfo());
                tbUserEggsAccumulateHistory.setSerialNumber(serialNumber);
                tbUserEggsAccumulateHistory.setBatchNo(maxBatchNo);
                tbUserEggsAccumulateHistory.setMobile(reqAdminAddEggsUser.getPhone());
                tbUserEggsAccumulateHistory.setApplyName(reqAdminAddEggs.getApplyName());
                tbUserEggsAccumulateHistory.setCheckNum(reqAdminAddEggs.getCheckNum());
                tbUserEggsAccumulateHistory.setpDescribe(tbAccumulateRuleList.get(0).getpDescribe());
                tbUserEggsAccumulateHistoryMapper.insertSelective(tbUserEggsAccumulateHistory);
                continue;
            }

            if(respUserInfoBaseAPIResponse.isRet()&&null!=respUserInfoBaseAPIResponse.getData()){
                String serialNumber = CommonUtils.generateBusinessOrderNo(Constants.ASSETS_SYSTEM, respUserInfoBaseAPIResponse.getData().getUid());
                //初始化账号
                userAssetsRepository.initAllCount(respUserInfoBaseAPIResponse.getData().getUid());
                //添加鸟蛋
                int count = eTbUserAssetsMapper.updateEffectiveAccumulate(respUserInfoBaseAPIResponse.getData().getUid(), AssetsType.ASSETS_EGGS.id.byteValue(), reqAdminAddEggsUser.getAccumulate());
                //鸟蛋历史记录
                TbUserEggsAccumulateHistory tbUserEggsAccumulateHistory = new TbUserEggsAccumulateHistory();
                tbUserEggsAccumulateHistory.setUid(respUserInfoBaseAPIResponse.getData().getUid());
                tbUserEggsAccumulateHistory.setAccumulate(reqAdminAddEggsUser.getAccumulate());
                tbUserEggsAccumulateHistory.setOpType(OpType.RECEIVE.id.byteValue());
                tbUserEggsAccumulateHistory.setBusinessCode(Constants.ASSETS_ADMIN_ADD_EGGS_CODE);
                tbUserEggsAccumulateHistory.setSystemCode(Constants.ASSETS_SYSTEM_CODE);
                tbUserEggsAccumulateHistory.setStatus(StatusType.EFFECTIVE.id.byteValue());
                tbUserEggsAccumulateHistory.setReceiver(respUserInfoBaseAPIResponse.getData().getNickName());
                tbUserEggsAccumulateHistory.setNickName(respUserInfoBaseAPIResponse.getData().getNickName());
                tbUserEggsAccumulateHistory.setPayReceive(AssetsPayReceive.SYSTEM.getName());
                tbUserEggsAccumulateHistory.setInfo(reqAdminAddEggs.getInfo());
                tbUserEggsAccumulateHistory.setSerialNumber(serialNumber);
                tbUserEggsAccumulateHistory.setBatchNo(maxBatchNo);
                tbUserEggsAccumulateHistory.setMobile(reqAdminAddEggsUser.getPhone());
                tbUserEggsAccumulateHistory.setApplyName(reqAdminAddEggs.getApplyName());
                tbUserEggsAccumulateHistory.setCheckNum(reqAdminAddEggs.getCheckNum());
                tbUserEggsAccumulateHistory.setpDescribe(tbAccumulateRuleList.get(0).getpDescribe());
                eggsAccumulateHistoryRepository.insertAccumulateHistory(tbUserEggsAccumulateHistory);
            }else{
                String serialNumber = CommonUtils.generateBusinessOrderNo(Constants.ASSETS_SYSTEM, -1);
                //记录失败
                TbUserEggsAccumulateHistory tbUserEggsAccumulateHistory = new TbUserEggsAccumulateHistory();
                tbUserEggsAccumulateHistory.setUid(-1);
                tbUserEggsAccumulateHistory.setAccumulate(reqAdminAddEggsUser.getAccumulate());
                tbUserEggsAccumulateHistory.setOpType(OpType.RECEIVE.id.byteValue());
                tbUserEggsAccumulateHistory.setBusinessCode(Constants.ASSETS_ADMIN_ADD_EGGS_CODE);
                tbUserEggsAccumulateHistory.setSystemCode(Constants.ASSETS_SYSTEM_CODE);
                tbUserEggsAccumulateHistory.setStatus(StatusType.DISABLE.id.byteValue());
                tbUserEggsAccumulateHistory.setPayReceive(AssetsPayReceive.SYSTEM.getName());
                tbUserEggsAccumulateHistory.setInfo(reqAdminAddEggs.getInfo());
                tbUserEggsAccumulateHistory.setSerialNumber(serialNumber);
                tbUserEggsAccumulateHistory.setBatchNo(maxBatchNo);
                tbUserEggsAccumulateHistory.setMobile(reqAdminAddEggsUser.getPhone());
                tbUserEggsAccumulateHistory.setApplyName(reqAdminAddEggs.getApplyName());
                tbUserEggsAccumulateHistory.setCheckNum(reqAdminAddEggs.getCheckNum());
                tbUserEggsAccumulateHistory.setpDescribe(tbAccumulateRuleList.get(0).getpDescribe());
                tbUserEggsAccumulateHistoryMapper.insertSelective(tbUserEggsAccumulateHistory);
            }
        }
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse<PageObj<List<RespAdminAddEggs>>> queryAddEggs(ReqAdminAddEggsQuery reqAdminAddEggsQuery) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取鸟蛋历史查询条件
        TbUserEggsAccumulateHistoryExample tbUserEggsAccumulateHistoryExample=new TbUserEggsAccumulateHistoryExample();
        TbUserEggsAccumulateHistoryExample.Criteria criteria= tbUserEggsAccumulateHistoryExample.createCriteria();
        if(null!=reqAdminAddEggsQuery.getBatchNo()){
            criteria.andBatchNoEqualTo(reqAdminAddEggsQuery.getBatchNo());
        }else{
            criteria.andBatchNoGreaterThan(0);
        }
        if(!StringUtil.isBlankOrNull(reqAdminAddEggsQuery.getSerialNumber())){
            criteria.andSerialNumberLike("%" + reqAdminAddEggsQuery.getSerialNumber() + "%");
        }
        if(!StringUtil.isBlankOrNull(reqAdminAddEggsQuery.getMobile())){
            criteria.andMobileLike("%" + reqAdminAddEggsQuery.getMobile() + "%");
        }
        if(null!=reqAdminAddEggsQuery.getStatus()){
            criteria.andStatusEqualTo(reqAdminAddEggsQuery.getStatus());
        }
        if(!StringUtil.isBlankOrNull(reqAdminAddEggsQuery.getStartCreateTime())){
            criteria.andCreateTimeGreaterThanOrEqualTo(sdf.parse(reqAdminAddEggsQuery.getStartCreateTime()));
        }
        if(!StringUtil.isBlankOrNull(reqAdminAddEggsQuery.getEndCreateTime())){
            criteria.andCreateTimeLessThanOrEqualTo(sdf.parse(reqAdminAddEggsQuery.getEndCreateTime()));
        }
        if(!StringUtil.isBlankOrNull(reqAdminAddEggsQuery.getInfo())){
            criteria.andInfoLike("%" + reqAdminAddEggsQuery.getInfo() + "%");
        }
        if(!StringUtil.isBlankOrNull(reqAdminAddEggsQuery.getApplyName())){
            criteria.andApplyNameLike("%" + reqAdminAddEggsQuery.getApplyName() + "%");
        }
        if(!StringUtil.isBlankOrNull(reqAdminAddEggsQuery.getCheckNum())) {
            criteria.andCheckNumLike("%" + reqAdminAddEggsQuery.getCheckNum() + "%");
        }
        int count=tbUserEggsAccumulateHistoryMapper.countByExample(tbUserEggsAccumulateHistoryExample);
        reqAdminAddEggsQuery.setPageNo(reqAdminAddEggsQuery.getPageNo()*reqAdminAddEggsQuery.getPageSize());
        //设置分页
        List<RespAdminAddEggs> userEggsAccumulateHistoryList=eTbUserEggsAccumulateHistoryMapper.getAdminAddEggs(reqAdminAddEggsQuery);
        PageObj<List<RespAdminAddEggs>> pageObj = PageObj.create(count, reqAdminAddEggsQuery.getPageNo()/reqAdminAddEggsQuery.getPageSize(), reqAdminAddEggsQuery.getPageSize(), userEggsAccumulateHistoryList);
        return APIResponse.returnSuccess(pageObj);

    }

    private String rechangeHistory(RespUserInfoBase respUserInfoBase, ReqEggsRechange reqEggsRechange) {
        String serialNumber=CommonUtils.generateBusinessOrderNo(Constants.ASSETS_SYSTEM, respUserInfoBase.getUid());
        TbUserEggsAccumulateHistory tbUserEggsAccumulateHistory=new TbUserEggsAccumulateHistory();
        tbUserEggsAccumulateHistory.setUid(respUserInfoBase.getUid());
        tbUserEggsAccumulateHistory.setNickName(respUserInfoBase.getNickName());
        tbUserEggsAccumulateHistory.setMobile(respUserInfoBase.getMobile());
        tbUserEggsAccumulateHistory.setAccumulate(reqEggsRechange.getOrderAmount().divide(currencyService.exchangeRatioById(AssetsType.ASSETS_EGGS.id.byteValue()).getData()).longValue());
        tbUserEggsAccumulateHistory.setOpType(OpType.RECEIVE.id.byteValue());
        tbUserEggsAccumulateHistory.setSerialNumber(serialNumber);
        if(reqEggsRechange.getPayId().intValue()== AssetsPayReceive.ALIRECHARGE.id.intValue()){
            tbUserEggsAccumulateHistory.setPayReceive(AssetsPayReceive.ALIRECHARGE.getName());
        }else{
            tbUserEggsAccumulateHistory.setPayReceive(AssetsPayReceive.WEIXRECHARGE.getName());
        }
        tbUserEggsAccumulateHistory.setPlatFormType(reqEggsRechange.getPlatformType());
        tbUserEggsAccumulateHistory.setReceiver("百灵鸟");
        tbUserEggsAccumulateHistory.setExpireTime(DateUtils.addTime(new Date(),10,DateUtils.TIME_TYPE_MINUTE));
        tbUserEggsAccumulateHistory.setInfo("鸟蛋充值,1元="+utilCurrencyService.exchangeAssetsAmount(AssetsType.ASSETS_EGGS.id.byteValue()).longValue()+"鸟蛋");
        tbUserEggsAccumulateHistory.setSystemCode(Constants.ASSETS_SYSTEM_CODE);
        tbUserEggsAccumulateHistory.setBusinessCode(Constants.ASSETS_EGGS_RECHANGE_CODE);
        tbUserEggsAccumulateHistory.setStatus(StatusType.RECHARGE.id.byteValue());
        eggsAccumulateHistoryRepository.insertSelective(tbUserEggsAccumulateHistory);
        return serialNumber;

    }
}
